<template>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large" @keyup.enter="login">
        <el-form-item prop="user">
            <el-input v-model="form.username" prefix-icon="user" clearable placeholder="输入用户名">
            </el-input>
        </el-form-item>

        <el-form-item prop="password">
            <el-input v-model="form.password" prefix-icon="lock" clearable show-password placeholder="输入密码"></el-input>
        </el-form-item>

        <el-form-item>
            <div class="boxCode">
                <el-input v-model="form.captcha" prefix-icon="el-icon-CircleCheck" clearable placeholder="请输入验证码"
                    class="plinpnt"></el-input>
                <el-image :src="captchas.url" @click="getCodeApi" class="code"></el-image>
            </div>
        </el-form-item>

        <el-form-item style="margin-bottom: 10px;">
            <el-col :span="12">
                <el-checkbox v-model="checkPassword">记住密码</el-checkbox>
            </el-col>
            <el-col :span="12" class="login-forgot">
                <router-link to="/reset_password">忘记密码</router-link>
            </el-col>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" style="width: 100%;" round @click="login">登录</el-button>
        </el-form-item>

    </el-form>
</template>

<script setup>
import { ref, reactive, onBeforeMount } from 'vue'
//api
import { getCaptcha, userLogin } from '../../api/login'
//aes
import { Encrypt } from '../../utils/aes'
import { useUserStore } from '../../stores/index'
import { useMenuStore } from '../../stores/menu'


//表单数据
const form = reactive({
    username: '',
    password: '',
    captcha: ''
})
//表单验证
const rules = reactive({

})
//记住密码
let checkPassword = ref(false);
//验证码
let captchas = reactive({
    url: '',
    key: ''
})


//生命周期
onBeforeMount(() => {
    getCodeApi();
})

//生成验证码
const getCodeApi = async () => {
    const key = new Date().getTime().toString();
    captchas.key = key;
    const res = await getCaptcha({ key })
    let blob = new Blob([res], { type: 'application/vnd.ms-excel' });
    let imgUrl = URL.createObjectURL(blob);
    captchas.url = imgUrl;
}

//登录
const login = async () => {

    let res = await userLogin({
        username: Encrypt(form.username),
        password: Encrypt(form.password),
        key: captchas.key,
        captcha: form.captcha
    })
    if (res.code === 200) {
        // 存储token
        localStorage.setItem('token', res.data)
        // 获取用户信息
        await useUserStore().getUserInfo()
        // 获取路由
        await useMenuStore().getMenu()
    }
}
</script>

<style>
.boxCode {
    display: flex;
    align-items: center;
    width: 100%;
}

.code {
    margin-left: 10px;
    height: 40px;
    cursor: pointer;
}
</style>